﻿/*
 * Module:   基础架构 - Json工具
 * Function: Json工具(序列化与反序列化) 
 * Author:   Kelvin Gu
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace LordJS.Extensions
{
    public static class JsonUtil
    {
        public static T DeserializeObject<T>(string json)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                T jsonObject = (T)ser.ReadObject(ms);

                return jsonObject;
            }
        }

        public static string SerializeObject<T>(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);

                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}
